"""
Thread to accept a single connection for a ListenChannel

Copyright (c) 2009 Christopher Hesse
http://code.google.com/p/python-expect/
"""

import threading
import select


class AcceptThread(threading.Thread):
    """
    This thread waits for a connection to be made to the server_socket,
    accepts it, and then terminates.
    """
    
    def __init__(self, server_socket, terminate_selectable, connected_event):
        super(AcceptThread, self).__init__()
        self.server_socket = server_socket
        self.terminate_selectable = terminate_selectable
        self.connected_event = connected_event
        
    def run(self):
        # for some reason, the coverage module doesn't seem to notice that
        # the .run() method of a thread is in fact called
        return self.accept_connection() # pragma: no cover
        
    def accept_connection(self):
        # wait for either the server socket or the terminate selectable
        readable, _writable, _other = \
            select.select([self.server_socket, self.terminate_selectable], [], [])
        
        # if the terminate selectable is readable, that means we should exit this
        # thread, the owning ListenChannel has probably been closed
        if self.terminate_selectable in readable:
            return
        
        # if the server socket is readable, that means we have a pending
        # connection to accept
        if self.server_socket in readable:
            self.socket, _address = self.server_socket.accept()
            self.connected_event.set()